/*
 * @Description:
 * @Author: lixx
 * @Date: 2025-09-28 14:15:29
 * @LastEditTime: 2025-09-28 16:49:23
 * @LastEditors: lixx
 */
import Mock from "mockjs";
let List = [];
const count = 200;
// 模拟200条用户数据
for (let i = 0; i < count; i++) {
  List.push(
    Mock.mock({
      id: Mock.Random.guid(),
      name: Mock.Random.cname(),
      addr: Mock.mock("@county(true)"),
      "age|18-60": 1,
      birth: Mock.Random.date(),
      sex: Mock.Random.integer(0, 1),
    })
  );
}

// 获取搜索内容
function param2Obj(url) {
  const search = url.split("?")[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"') +
      '"}'
  );
}

export default {
  /**
   * 获取列表
   * 要带参数 name,page,limit;name：可以不填，page,limit有默认值
   * @params name,page,limit
   * @return {{code:number,count:number,data:*[]}}
   * **/
  getUserList: (config) => {
    const { name, page = 1, limit = 10 } = param2Obj(config.url);
    const mockList = List.filter((user) => {
      if (name && user.name.indexOf(name) === -1) return false;
      return true;
    });
    // 分页
    const pageList = mockList.filter(
      (item, index) => index < limit * page && index >= limit * (page - 1)
    );
    return {
      code: 200,
      data: {
        list: pageList,
        count: mockList.length,
      },
    };
  },
  /**
   *  删除用户
   *  @param id
   *  @return {*}
   *
   * **/
  deleteUser: (config) => {
    const { id } = param2Obj(config.url);
    if (!id) {
      return {
        code: -999,
        message: "参数不正确",
      };
    } else {
      List = List.filter((o) => o.id != id);
      return {
        code: 200,
        message: "删除成功",
      };
    }
  },

  /**
   *  增加用户
   *  @param name ,age,sex,addr,birth
   *  @return {}
   * **/
  creatUser: (config) => {
    const { name, age, sex, addr, birth } = JSON.parse(config.body);
    List.unshift({
      id: Mock.Random.guid(),
      name: name,
      sex: Number(sex),
      age: age,
      birth: birth,
      addr: addr,
    });
    return {
      code: 200,
      data: {
        message: "添加用户成功",
      },
    };
  },

  /**
   *  编辑用户
   *  @param {id,name,addr,birth,sex}
   *  @return
   * ***/
  updateUser: (config) => {
    const { id, name, sex, age, addr, birth } = JSON.parse(config.body);
    const sex_num = parseInt(sex);
    List.some((u) => {
      if (u.id === id) {
        u.name = name;
        u.addr = addr;
        u.age = age;
        u.birth = birth;
        u.sex = sex_num;
        return true;
      }
    });
    return {
      code: 200,
      data: {
        message: "编辑成功",
      },
    };
  },
};
